package com.weim.study.shiro.config;

import com.weim.study.shiro.entity.Permission;
import com.weim.study.shiro.entity.Role;
import com.weim.study.shiro.entity.User;
import com.weim.study.shiro.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class MyShiroRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("--->  角色权限和对应权限添加 ");

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        User user =  (User) principalCollection.getPrimaryPrincipal();

        user = userService.findByUsername(user.getUsername());

        //添加角色和权限
        for (Role role : user.getRoleList()) {
            //添加角色
            authorizationInfo.addRole(role.getRole());
            for(Permission permission : role.getPermissionList()) {
                //添加权限
                authorizationInfo.addStringPermission(permission.getPermission());
            }
        }

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        logger.info("---> 主要是用来进行身份认证的，验证用户输入的账号和密码是否正确");
        //获取用户的输入的账号
        String username = (String) authenticationToken.getPrincipal();

        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        User user = userService.findByUsername(username);
        logger.info("---> 验证用户的信息：" + user.toString());
        if(user == null){
            return null;
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user, //用户名
                user.getPassword(), //密码
                ByteSource.Util.bytes(user.getCredentialsSalt()),//salt=username+salt
                getName()  //realm name
        );
        return authenticationInfo;
    }
}